package service

import (
	"mutu/misc"
	"mutu/misc/cstore"
	"mutu/misc/log"
	"mutu/models"
)

type ResourceManager struct {
}

var (
	ResourceService = ResourceManager{}
)

func (p ResourceManager) SaveResource(r *models.Resource) error {
	if r.Uuid == "" {
		r.Uuid = misc.NewUUID()
	}
	_, err := models.Orm.Insert(r)
	if err != nil {
		log.Log.Error("保存资源出错，%s", err)
		return err
	}
	return nil
}

func (p ResourceManager) GetUserResourceByFlag(flag int, uuid string) ([]*models.Resource, error) {
	var arr []*models.Resource
	_, err := models.Orm.QueryTable("Resource").Filter("Flag", flag).Filter("UserId", uuid).All(&arr)
	if err != nil {
		log.Log.Error("读取用户<%s>, 类型<%d>资源出错，%s", uuid, flag, err)
		return nil, err
	}
	for _, item := range arr {
		item.Link = cstore.GetBaseUrl(item.Public, item.Key)
	}
	return arr, nil
}

func (p ResourceManager) GetResourceByUuid(uuid string) (*models.Resource, error) {
	item := &models.Resource{
		Uuid: uuid,
	}
	err := models.Orm.Read(item, "Uuid")
	if err != nil {
		log.Log.Error("读取<%s>资源出错，%s", uuid, err)
		return nil, err
	}
	item.Link = cstore.GetBaseUrl(item.Public, item.Key)
	return item, nil
}

func (p ResourceManager) UpdateResourceUsedBy(uuid, usedby string) error {
	r := &models.Resource{
		Uuid: uuid,
	}
	if err := models.Orm.Read(r, "Uuid"); err != nil {
		log.Log.Error("读取<%s>资源出错，%s", uuid, err)
		return err
	}
	r.UsedBy = usedby
	if _, err := models.Orm.Update(r, "UsedBy", "UpdateAt"); err != nil {
		log.Log.Error("更新<%s>资源出错，%s", uuid, err)
		return err
	}
	return nil
}
